/*
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:25
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-08-29 13:30:29
 * @FilePath: \ahbs\uc_sys\src\config\axios\index.ts
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved.
 */
import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosRequestHeaders,
  AxiosResponse,
  AxiosError
} from 'axios'

import { ElMessage, ElMessageBox } from 'element-plus'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()

import { useTagsViewStore } from '@/store/modules/tagsView'
const tagsViewStore = useTagsViewStore()

import { resetRouter } from '@/router'

import qs from 'qs'

import { config } from '@/config/axios/config'

const { result_code, overdue_code } = config

export const PATH_URL = import.meta.env.VITE_API_URL
// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: PATH_URL, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // lee 判断url是否是http开头
    // if (config.url.substr(0, 4) == 'http') {
    //   config.baseURL = ''
    // }
    // lee 这里的东西东西迟早需要处理，先放放
    if (
      // /user/loginOut 已处理
      config.url == '/analysis/userAccessSource' ||
      config.url == '/analysis/weeklyUserActivity' ||
      config.url == '/analysis/monthlySales' ||
      config.url == '/analysis/total'
    ) {
      config.baseURL = ''
    }
    if (config.data.data && config.data.data.my_org_id == undefined) {
      config.data.data.my_org_id = wsCache.get('my_org_id')
      config.data.data.admin_org_id = wsCache.get('my_org_id')
    } else {
      config.data.my_org_id = wsCache.get('my_org_id')
      config.data.admin_org_id = wsCache.get('my_org_id')
    }
    if (
      config.method === 'post' &&
      (config.headers as AxiosRequestHeaders)['Content-Type'] ===
        'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data)
    }

    // get参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url as string
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<Recordable>) => {
    if (response.data.code === result_code) {
      ElMessage({
        message: response.data.msg,
        type: 'success'
      })
      return response.data
    } else if (response.data.code === overdue_code) {
      loginOut(response.data.msg)
    } else {
      // ElMessage.error(response.data.message)
      ElMessage.error(response.data.msg)
    }
  },
  (error: AxiosError) => {
    console.log('err' + error) // for debug
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

const loginOut = (mes: string) => {
  ElMessageBox.confirm(mes, '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      wsCache.clear()
      tagsViewStore.delAllViews()
      resetRouter() // 重置静态路由表
      location.reload() // 刷新页面
    })
    .catch(() => {})
}

export { service }
export default service
